import request from '@/utils/request'
import { uploadDownload } from '@/api/uploadImg'
import { getToken, removeToken } from '@/utils/auth'

/**
 * 接口下载方法
 */
export function downloadInterface(params = {}) {
  fetch(process.env.VUE_APP_BUSINESS_API + '/kmpt/biz/download/new', {
    method: 'post',
    body: JSON.stringify(params),
    headers: {
      'Authorization': `Bearer ${getToken()}`,
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }).then(function(response) {
    var filename = null
    try {
      filename = response.headers.get('Content-Disposition').split(';')[1].split('=')[1].replace(/"/g, '')
      filename = decodeURIComponent(filename)
    } catch (e) {
    }
    // finally{
    //   if(filename == null){
    //     let date = new Date();
    //     filename = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}.xls`;
    //   }
    // }
    response.blob().then(blob => {
      const link = document.createElement('a')
      link.style.display = 'none'
      // a 标签的 download 属性就是下载下来的文件名
      if (filename != null) {
        link.download = filename
      }
      console.log(filename)
      link.href = URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      // 释放的 URL 对象以及移除 a 标签
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    })
  })
}

/**
 * 链接下载方法
 * @param url
 */
export function linkDownload(url) {
  const linkDown = document.createElement('a')
  linkDown.style.display = 'none'
  linkDown.href = url
  document.body.appendChild(linkDown)
  linkDown.click()
  // 释放的 URL 对象以及移除 a 标签
  URL.revokeObjectURL(linkDown.href)
  document.body.removeChild(linkDown)
}
